//
//  LoginViewController.m
//  TanYiShan
//
//  Created by Chan on 2/26/14.
//  Copyright (c) 2014 Chan. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.loginWebView.delegate = self;
    self.messageTextView.delegate = self;
    [self checkHasBeenLogin];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)checkHasBeenLogin {
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    //[config removeObjectForKey:@"access_token"];
    NSString *access_token = [config stringForKey:@"access_token"];
    if (access_token == Nil) {
        [self showLoginWebView:Nil];
    } else {
        _access_token = access_token;
    }
}

- (IBAction)showLoginWebView:(id)sender {
    
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=arEzhavVFyotayGAw9G8&redirect_uri=http://127.0.0.1/tys/callback.php"]];
    [self.loginWebView loadRequest:request];
    [self.loginWebView setHidden:NO];
//    [self.loginWebView setScalesPageToFit:YES];
    [self.view insertSubview:self.loginWebView aboveSubview:self.view];
    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    
//    NSString *authorizeUrl = @"https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=";
//    authorizeUrl = [authorizeUrl stringByAppendingFormat:@"%@%@",APP_CLIENT_ID,@"&redirect_uri=http://127.0.0.1/tys/callback.php"];
//    
//    [manager GET:authorizeUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"JSON: %@", responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"Error: %@", error);
//    }];

}

-(void)showUserInfos {
    
    NSString *url = [[NSString alloc] initWithFormat:@"%@%@",OPEN_API_URL_BASE,OPEN_API_USER_INFORMATION];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:_access_token forKey:@"access_token"];
    [params setObject:@"json" forKey:@"dataType"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        UIAlertView *myInformationAlert = [[UIAlertView alloc] initWithTitle:@"个人信息" message:[responseObject objectForKey:@"name"] delegate:Nil cancelButtonTitle:@"确定" otherButtonTitles:Nil, nil];
        [myInformationAlert show];
        NSLog(@"%@",responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {

    NSLog(@"Load Finished");
    NSString *loginResult = webView.request.URL.absoluteURL.absoluteString;
    NSLog(@"%@",loginResult);
    
    //JSONDecoder *jd = [[JSONDecoder alloc] init];

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"Load Failed");
    NSString *loginResult = [[error.userInfo objectForKey:@"NSErrorFailingURLKey"] absoluteString];
    
    NSRange rangeOfCode = [loginResult rangeOfString:@"code"];
    NSString *code = [loginResult substringWithRange:NSMakeRange(rangeOfCode.location + 5, 6)];
    if (code != Nil) {
        NSLog(@"%@",code);
        NSString *authorizeUrl = @"https://www.oschina.net/action/openapi/token?client_secret=8UWCDYzjg6he9CQTKtVeqp4UV8rvlZ7c&client_id=arEzhavVFyotayGAw9G8&grant_type=authorization_code&redirect_uri=http://127.0.0.1/tys/callback.php&dataType=json";
        authorizeUrl = [authorizeUrl stringByAppendingFormat:@"&code=%@",code];
        
        //NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:authorizeUrl]];
        
        //[webView loadRequest:request];
        
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
            [manager GET:authorizeUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"JSON: %@", responseObject);
                [webView setHidden:YES];
                NSString *access_token = [responseObject objectForKey:@"access_token"];
                if (access_token) {
                    
                    _access_token = access_token;
                    
                    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
                    [config setObject:access_token forKey:@"access_token"];
                    [config synchronize];
                     NSLog(@"access_token:%@",[responseObject objectForKey:@"access_token"]);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"Error: %@", error);
            }];
        
//        [webView removeFromSuperview];
    } else {
     NSLog(@"授权失败");
    }
}
- (IBAction)showUserInformationAction:(id)sender {
    [self showUserInfos];
}
    
- (IBAction)postMessage:(id)sender {
    NSString *url = [[NSString alloc] initWithFormat:@"%@%@",OPEN_API_URL_BASE,OPEN_API_TWEET_PUB];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:_access_token forKey:@"access_token"];
    [params setObject:[self.messageTextView text] forKey:@"msg"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *result = (NSDictionary *)responseObject;
        NSString *status = [result objectForKey:@"error"];
        
        if([status isEqualToString:@"200"]){
            UIAlertView *responseAlert = [[UIAlertView alloc] initWithTitle:@"通知" message:@"发布成功" delegate:Nil cancelButtonTitle:@"确定" otherButtonTitles:Nil, nil];
            [responseAlert show];
            NSLog(@"%@",responseObject);
        } else if([status isEqualToString:@"500"]){
            UIAlertView *responseAlert = [[UIAlertView alloc] initWithTitle:@"通知" message:@"发布失败，字数不能为空" delegate:Nil cancelButtonTitle:@"确定" otherButtonTitles:Nil, nil];
            [responseAlert show];
            NSLog(@"%@",responseObject);
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
    
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
        if (1 == range.length) {//按下回格键
            return YES;
        }
        
        if ([text isEqualToString:@"\n"]) {//按下return键
            //这里隐藏键盘，不做任何处理
            [textView resignFirstResponder];
            [self postMessage:textView];
            [textView setText:@""];
            return NO;
        }else {
            if ([textView.text length] < 140) {//判断字符个数
                return YES;
            }  
        }
        return NO;
    }
@end
